package com.ecsolutions.controller;

import com.ecsolutions.Validators.LoanApplicationValidate;
import com.ecsolutions.Validators.UtilizationValidate;
import com.ecsolutions.common.Lixijisuan;
import com.ecsolutions.common.ObjectHelp;
import com.ecsolutions.entity.*;
import com.ecsolutions.service.ExaminationService;
import com.ecsolutions.service.Utilization_Service;
import com.ecsolutions.soaClient.TransferClient;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/7/31.
 */
@SuppressWarnings("all")
@Controller
public class Utilization_Controller {

    public Utilization_Controller(){}

    @Autowired
    private Utilization_Service utilization_service;

    @Autowired
    private ExaminationService examinationService;

    @Autowired
    private TransferClient client;

    @InitBinder("utilization_entity")
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new UtilizationValidate(utilization_service));
    }

    @InitBinder("applicationInfo_entity")
    public void initBinderTwo(WebDataBinder binder) {
        binder.setValidator(new LoanApplicationValidate());
    }

    /*进入使用信息页面*/
    @GetMapping("/UtilizationList")
    public String getUtilizationPage(Model model){
        String custcod = "188688000007";
        String bpm_no = "BP1Y10000079";
        Utilization_Entity utilization_entity = new Utilization_Entity();
        Random random = new Random();
        String index = String.valueOf(random.nextInt(1000000))+String.valueOf(random.nextInt(100000));
        int i = index.length();
        String loanstr = "";
        for(int j=1;j<=11-i;j++){
            loanstr = loanstr+"0";
        }
        String loanref = "LN"+loanstr+String.valueOf(index);
        utilization_entity.setLoanref(loanref);
        utilization_entity.setCustcod(custcod);
        utilization_entity.setBpm_no(bpm_no);
        model.addAttribute("utilization_entity", utilization_entity);
        model.addAttribute("utilization_info", utilization_service.getPopupInfo());
        //利率信息
        List<HashMap<String,Object>> ratetypeList = new ArrayList<HashMap<String,Object>>();
        HashMap<String,Object> ratetypemap = new HashMap<String,Object>();
        ratetypemap.put("RATETYP","");
        ratetypemap.put("INTRTPA","");
        ratetypeList.add(ratetypemap);
        model.addAttribute("ratetype_info",ratetypeList);
        //大类信息
        List<HashMap<String,String>> daleiList = new ArrayList<HashMap<String,String>>();
        HashMap<String,String> daleimap = new HashMap<String,String>();
        daleimap.put("DALEI","");
        daleimap.put("LEIBIEMINGCHENG","");
        daleiList.add(daleimap);
        model.addAttribute("dalei_info",daleiList);
        //中类信息
        List<HashMap<String,String>> zhongleiList = new ArrayList<HashMap<String,String>>();
        HashMap<String,String> zhongleimap = new HashMap<String,String>();
        zhongleimap.put("ZHONGLEI","");
        zhongleimap.put("LEIBIEMINGCHENG","");
        zhongleiList.add(zhongleimap);
        model.addAttribute("zhonglei_info",zhongleiList);
        //小类信息
        List<HashMap<String,String>> xiaoleileiList = new ArrayList<HashMap<String,String>>();
        HashMap<String,String> xiaoleimap = new HashMap<String,String>();
        xiaoleimap.put("XIAOLEI","");
        xiaoleimap.put("LEIBIEMINGCHENG","");
        xiaoleileiList.add(xiaoleimap);
        model.addAttribute("xiaolei_info",xiaoleileiList);
        //计算
        double rate = 0.0615;
        int totalMoney = 200000;
        int year = 1;
        Lixijisuan jisuan = new Lixijisuan();
        jisuan.interest(totalMoney,rate,year);

        return "Utilization/utilization";
    }

    /*通过custcod查询信息到Table表格中*/
    @ResponseBody
    @RequestMapping(value = "/UtilizationListInfo",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
    public List<Utilization_Entity> getUtilizationInfoList(@RequestBody Map<String, Object> map ){
        String custcod = map.get("custcod").toString();
        List<Utilization_Entity> utilization_entitieList = utilization_service.getByCustcodInfo(custcod);
        return utilization_entitieList;
    }

    /*通过custcod和loanref查询信息到还款计划表格中*/
    @ResponseBody
    @RequestMapping(value = "/payList",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
    public List<Pay_Entity> getPayList(@RequestBody Map<String, Object> map ){
        String custcod = map.get("custcod").toString();
        String loanref = map.get("loanref").toString();
        List<Pay_Entity> payList = utilization_service.getPayList(custcod,loanref);
        return payList;
    }

    /*通过custcod和lineno查询出数据*/
    @ResponseBody
    @RequestMapping(value = "/getFacilityInfo",method = RequestMethod.POST)
    public Facility_Entity getFacilityInfoByCustcodAndLineno(String custcod,String lineno){
        Facility_Entity facility_entity = utilization_service.getFacilityInfoByCustcodAndLineno(custcod,lineno);
        return facility_entity;
    }

    /*通过custcode查询出数据*/
    @ResponseBody
    @RequestMapping(value = "/selectDuicustcd",method = RequestMethod.POST)
    public HashMap<String,String> selectDuicustcd(String custcode){
        HashMap<String,String> map = utilization_service.getApplicationInfo(custcode);
        return map;
    }

    /*查询出信息跳转到使用-出账通知单页面*/
    @RequestMapping(value = "/getPayPlan",method = RequestMethod.GET)
    public String getPayPlanInfo(String custcode,String line_no,String loanref,Model model){
        Utilization_Entity utilization_entity = utilization_service.getUtilizationByCustcodAndLineno(custcode,line_no,loanref);
        String custcod = custcode;
        String lineno = line_no;
        String bpm_no = utilization_service.getFacilityInfoByCustcodAndLineno(custcod,lineno).getBpm_no();
        String remark = utilization_service.getFacilityInfoByCustcodAndLineno(custcod,lineno).getRemark();
        utilization_entity.setBpm_no(bpm_no);
        String lastName = utilization_service.getLastName(custcode);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String DueDate = sdf.format(utilization_entity.getDuedate());
        model.addAttribute("lastName",lastName);
        model.addAttribute("DueDate",DueDate);
        model.addAttribute("remark",remark);
        model.addAttribute("utilization_entity",utilization_entity);
        return "Utilization/payPlan";
    }

    /*查询出信息跳转到使用-还款计划表页面*/
    @RequestMapping(value = "/getPay",method = RequestMethod.GET)
    public String getPay(String custcode,String line_no,String loanref,Model model){
        String custcod = custcode;
        String lineno = line_no;
        Utilization_Entity utilization_entity =utilization_service.getUtilizationByCustcodAndLineno(custcod,lineno,loanref);
        model.addAttribute("utilization_entity",utilization_entity);
        return "Utilization/pay";
    }

    /*查询出信息跳转到使用客户申请信息页面*/
    @RequestMapping(value = "/getApplicationInfo",method = RequestMethod.GET)
    public String getLoanApplicationInfo(String custcode,String line_no,String loanref,Model model){
        ApplicationInfo_Entity applicationInfo_entity1 = utilization_service.getByLoanrefInfo(loanref);
        if(applicationInfo_entity1==null){
            ApplicationInfo_Entity applicationInfo_entity = new ApplicationInfo_Entity();
            applicationInfo_entity.setCustcode(custcode);
            applicationInfo_entity.setLine_no(line_no);
            applicationInfo_entity.setLoanref(loanref);
            model.addAttribute("applicationInfo_entity",applicationInfo_entity);
        }else{
            model.addAttribute("applicationInfo_entity",applicationInfo_entity1);
        }
        return "LoanApplicationInfo/loanApplicationInfo";
    }

    /*保存或者更新客户申请信息*/
    @RequestMapping(value = "/saveApplicationInfo",method = RequestMethod.POST)
    public String saveORupdateLoanApplicationInfo(@Valid @ModelAttribute("applicationInfo_entity") ApplicationInfo_Entity applicationInfo_entity,BindingResult result,Model model){
        model.addAttribute("applicationInfo_entity",applicationInfo_entity);
        if(!result.hasErrors()) {
            ApplicationInfo_Entity applicationInfo_entity1 = utilization_service.getByLoanrefInfo(applicationInfo_entity.getLoanref());
            if (applicationInfo_entity1 == null) {
                utilization_service.saveApplicationInfo(applicationInfo_entity);
            } else {
                utilization_service.updateApplicationInfo(applicationInfo_entity);
            }
            return "LoanApplicationInfo/loanApplicationInfo";
        }
        return "LoanApplicationInfo/loanApplicationInfo";
    }

    /*查询出信息跳转到使用支付信息页面*/
    @RequestMapping(value = "/getApplicationPay",method = RequestMethod.GET)
    public String getApplicationPay(String custcode,String line_no,String loanref,String drawccy,String drawamt,String drawdate,Model model){
        Loanpaymentinfo_Entity loanpaymentinfo_entity1 = utilization_service.getLoanpaymentinfo(loanref);
        if(loanpaymentinfo_entity1==null){
            Loanpaymentinfo_Entity loanpaymentinfo_entity = new Loanpaymentinfo_Entity();
            loanpaymentinfo_entity.setCustCode(custcode);
            loanpaymentinfo_entity.setLineno(line_no);
            loanpaymentinfo_entity.setLoanRef(loanref);
            loanpaymentinfo_entity.setDrawccy(drawccy);
            loanpaymentinfo_entity.setDrawamt(drawamt);
            loanpaymentinfo_entity.setDrawdate(drawdate);
            String fenzhihang = utilization_service.getFenZhiHang(custcode);
            String lastname = utilization_service.getLastName(custcode);
            loanpaymentinfo_entity.setFenzhihang(fenzhihang);
            loanpaymentinfo_entity.setLastname(lastname);
            model.addAttribute("loanpaymentinfo_entity",loanpaymentinfo_entity);
        }else{
            model.addAttribute("loanpaymentinfo_entity",loanpaymentinfo_entity1);
        }
        Loanpaymentinfo_det_Entity loanpaymentinfo_det_entity = new Loanpaymentinfo_det_Entity();
        loanpaymentinfo_det_entity.setCustcode(custcode);
        loanpaymentinfo_det_entity.setLoanref(loanref);
        model.addAttribute("loanpaymentinfo_det_entity",loanpaymentinfo_det_entity);
        return "ApplicationPay/applicationPay";
    }

    /*保存或者更新使用支付信息*/
    @ResponseBody
    @RequestMapping(value = "/saveLoanapplicationPayInfo",method = RequestMethod.POST)
    public String saveORupdateLoanApplicationPayInfo(Loanpaymentinfo_Entity loanpaymentinfo_entity){
        String loanRef = loanpaymentinfo_entity.getLoanRef();
        if(utilization_service.getLoanpaymentinfo(loanRef)==null){
            utilization_service.saveLoanpaymentInfo(loanpaymentinfo_entity);
        }else{
            utilization_service.updateLoanpaymentInfo(loanpaymentinfo_entity);
        }
        return "保存成功";
    }

    /*保存或者更新使用支付信息2*/
    @ResponseBody
    @RequestMapping(value = "/saveLoanapplicationPayInfodet",method = RequestMethod.POST)
    public String saveORupdateLoanApplicationPayInfodet(Loanpaymentinfo_det_Entity loanpaymentinfo_det_entity){
        Integer id = loanpaymentinfo_det_entity.getId();
        if(id==null){
            Integer maxId = utilization_service.getMaxId();
            if(maxId==null){
                loanpaymentinfo_det_entity.setId(1);
            }else{
                loanpaymentinfo_det_entity.setId(1+maxId);
            }
            utilization_service.saveLoanpaymentInfodet(loanpaymentinfo_det_entity);
        }else{
            utilization_service.updateLoanpaymentInfodet(loanpaymentinfo_det_entity);
        }
        return String.valueOf(loanpaymentinfo_det_entity.getId());
    }

    /*通过custcode和loanRef查询信息到支付信息表格中*/
    @ResponseBody
    @RequestMapping(value = "/LoanpaymentinfoList",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
    public List<Loanpaymentinfo_det_Entity> getLoanpaymentinfoList(@RequestBody Map<String, Object> map ){
        String custcode = map.get("custcode").toString();
        String loanref = map.get("loanref").toString();
        List<Loanpaymentinfo_det_Entity> loanpaymentinfo_det_entities = utilization_service.getLoanpaymentinfoList(custcode,loanref);
        return loanpaymentinfo_det_entities;
    }

    /*通过放款币种值查询信息到利率类型下拉框*/
    @ResponseBody
    @RequestMapping(value = "/getliLvLeiXingInfo",method = RequestMethod.POST)
    public List<HashMap<String,Object>> getLiLvLeiXingInfoList(String drawccy){
        List<HashMap<String,Object>> liLvLeiXingList = utilization_service.getByLiLvInfo(drawccy);
        return liLvLeiXingList;
    }

    /*通过放款币种值和利率类型值查询信息到年利率框*/
    @ResponseBody
    @RequestMapping(value = "/getnianliLvLeiInfo",method = RequestMethod.POST)
    public String getNianLiLvLeiXingInfoList(String drawccy,String ratetype){
        String nianlilv = utilization_service.getNianlilvInfo(drawccy,ratetype);
        return nianlilv;
    }

    /*通过客户经理代码查询出经理名称*/
    @ResponseBody
    @RequestMapping(value = "/getJingLiMingChenInfo",method = RequestMethod.POST)
    public String getJingliMingChen(String accoffic){
        String jingLiMingChen = utilization_service.getJingLiMingChenInfo(accoffic);
        return jingLiMingChen;
    }

    /*通过门类值查询信息到大类下拉框*/
    @ResponseBody
    @RequestMapping(value = "/getDaleiInfo",method = RequestMethod.POST)
    public List<HashMap<String,String>> getDaleiInfoList(String dircflag1){
        List<HashMap<String,String>> daleiList = utilization_service.getByMenleiInfo(dircflag1);
        return daleiList;
    }

    /*通过门类和大类查询信息到中类下拉框*/
    @ResponseBody
    @RequestMapping(value = "/getZhongleiInfo",method = RequestMethod.POST)
    public List<HashMap<String,String>> getZhongleiInfoList(String dircflag1,String dircflag2){
        List<HashMap<String,String>> zhongleiList = utilization_service.getByMenleiAndDaleiInfo(dircflag1,dircflag2);
        return zhongleiList;
    }

    /*通过门类和大类和中类查询信息到小类下拉框*/
    @ResponseBody
    @RequestMapping(value = "/getXiaoleiInfo",method = RequestMethod.POST)
    public List<HashMap<String,String>> getXiaoleiInfoList(String dircflag1,String dircflag2,String dircflag3){
        List<HashMap<String,String>> xiaoleiList = utilization_service.getByMenleiAndDaleiAndZhongleiInfo(dircflag1,dircflag2,dircflag3);
        return xiaoleiList;
    }

    /*保存或更新使用信息*/
    @PostMapping("/UtilizationList")
    public String savePledgeInfo(@Valid @ModelAttribute("utilization_entity") Utilization_Entity utilization_entity, BindingResult result, Model model) {
        model.addAttribute("utilization_entity", utilization_entity);
        model.addAttribute("utilization_info", utilization_service.getPopupInfo());
        String custcod = utilization_entity.getCustcod();
        String lineno = utilization_entity.getLineno();
        String loanref = utilization_entity.getLoanref();
        if (!result.hasErrors()) {
            if (utilization_service.getUtilizationByCustcodAndLineno(custcod, lineno, loanref) == null) {
                System.out.println("对象为空");
                //计算出到期日
                Date duedate = utilization_service.getDuedateByUtilizationInfo(utilization_entity);
                utilization_entity.setDuedate(duedate);
                utilization_service.saveUtilizationInfo(utilization_entity);
                //授信表中金额处理
                Integer lineamt = utilization_entity.getLineamt();
                Integer drawamt = utilization_entity.getDrawamt();
                Facility_Entity facility_entity = utilization_service.getFacilityInfoByCustcodAndLineno(custcod, lineno);
                if (facility_entity.getOsamt() == 0) {
                    Integer osamt = lineamt;//余额
                    Integer avliamt = lineamt;//可用额度
                    String linestatus = "2";
                    Boolean aBoolean = utilization_service.updateFacilityInfo(osamt, avliamt, linestatus, custcod, lineno);
                    if (aBoolean == true) {
                        System.out.println("更新成功");
                    } else {
                        System.out.println("更新失败");
                    }
                } else {
                    String linestatus = "2";
                    Integer avliamt = facility_entity.getAvliamt() - utilization_entity.getDrawamt();
                    Integer holdamt = facility_entity.getHoldamt() + utilization_entity.getDrawamt();
                    Boolean aBoolean = utilization_service.updateFacilityInfoTwo(avliamt, holdamt, linestatus, custcod, lineno);
                    if (aBoolean == true) {
                        System.out.println("更新成功");
                    } else {
                        System.out.println("更新失败");
                    }
                }
            } else {
                System.out.println("对象非空");
                Date duedate = utilization_service.getDuedateByUtilizationInfo(utilization_entity);
                utilization_entity.setDuedate(duedate);
                utilization_service.updateUtilizationInfo(utilization_entity);
            }
            //生成还款计划表
//            double rate = Double.parseDouble(utilization_entity.getSchemarate());//调整后年利率
//            int totalMoney = utilization_entity.getDrawamt();//放款金额
//            int year = 1;//贷款年限
            double rate = 0.0615;
            int totalMoney = 200000;
            int year = 1;
            Lixijisuan jisuan = new Lixijisuan();
            jisuan.interest(totalMoney, rate, year);

            String drawccy = utilization_entity.getDrawccy();
            String dorcflag1 = utilization_entity.getDircflag1();
            String dorcflag2 = utilization_entity.getDircflag2();
            String dorcflag3 = utilization_entity.getDircflag3();
            String dorcflag4 = utilization_entity.getDircflag4();
            List<HashMap<String, Object>> ratetypeList = utilization_service.getRatetypeList(drawccy);
            model.addAttribute("ratetype_info", ratetypeList);
            List<HashMap<String, String>> daleiList = utilization_service.getDaleiList(dorcflag1);
            model.addAttribute("dalei_info", daleiList);
            List<HashMap<String, String>> zhongleiList = utilization_service.getZhongleiList(dorcflag1, dorcflag2);
            model.addAttribute("zhonglei_info", zhongleiList);
            List<HashMap<String, String>> xiaoleiList = utilization_service.getXiaoleiList(dorcflag1, dorcflag2, dorcflag3);
            model.addAttribute("xiaolei_info", xiaoleiList);

            return "Utilization/utilization";
        }
        return "Utilization/utilization";
    }

    /*点击新增按钮传递一个空对象到form表单*/
    @ResponseBody
    @RequestMapping(value = "/NewUtilizationInfo",method = RequestMethod.POST)
    public Utilization_Entity getNewFacilityInfo(String custcod){
        Utilization_Entity utilization_entity= new Utilization_Entity();
        //随机给定一个贷款编号
        Random random = new Random();
        String index = String.valueOf(random.nextInt(1000000))+String.valueOf(random.nextInt(100000));
        int i = index.length();
        String loanstr = "";
        for(int j=1;j<=11-i;j++){
            loanstr = loanstr+"0";
        }
        String loanref = "LN"+loanstr+String.valueOf(index);
        utilization_entity.setLoanref(loanref);
        return utilization_entity;
    }

    /*通过id删除抵押品信息*/
    @ResponseBody
    @RequestMapping(value = "/deleteUtilizationInfo",method = RequestMethod.POST)
    public Map<String,String> deleteUtilizationInfo(String custcod,String lineno,String loanref){
        Map<String, String> resultMap = new HashMap<>();
        utilization_service.deleteUtilizationInfo(custcod,lineno,loanref);
        resultMap.put("message","删除成功");
        return resultMap;
    }

    /*通过id删除使用支付信息*/
    @ResponseBody
    @RequestMapping(value = "/deleteLoanpaymentInfo",method = RequestMethod.POST)
    public String deleteLoanpaymentInfo(String id){
        utilization_service.deleteLoanpaymentInfo(Integer.parseInt(id));
        return "删除成功";
    }

    /*通过loanref导出还款计划表*/
    @ResponseBody
    @RequestMapping(value = "/derivarLoanpaymentInfo",method = RequestMethod.POST)
    public String derivarLoanpaymentInfo(String loanref, String custcod, String lineno, HttpServletRequest request, HttpServletResponse response){
        List<Pay_Entity> payList = utilization_service.getPayList(custcod,loanref);//还款计划表信息
        Utilization_Entity utilization_entity =utilization_service.getUtilizationByCustcodAndLineno(custcod,lineno,loanref);//使用表信息
        String result = utilization_service.derivarExcel(payList,utilization_entity);
        return result;
    }

}
